import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'
import { delCartApi, getNewCartApi, insertCartApi } from '@/apis/cart'
export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    // 判断是否登录
    const isLogin = computed(() => userStore.userInfo.token)

    // 获取最新购物车
    const updateNewCartList = async () => {
        const res = await getNewCartApi()
        cartList.value = res.result
    }
    const cartList = ref([])
    // 添加购物车
    const addCart = async (goods) => {
        const { skuId, count } = goods
        if (isLogin.value) {//登陆了：接口调用购物车
            // 加入购物车
            await insertCartApi({ skuId, count })
            // 获取最新购物车列表，并覆盖本地购物车
            const res = await getNewCartApi()
            cartList.value = res.result
        } else {//本地购物车逻辑
            // 已添加，count++（skuId是否存在）
            const item = cartList.value.find((item) => goods.skuId === item.skuId)
            if (item) {
                item.count++
            } else {
                // 未添加，push
                cartList.value.push(goods)
            }
        }

    }
    // 删除购物车商品
    const delCart = async (skuId) => {
        if (isLogin.value) {
            await delCartApi([skuId])
            // 删除后获取最新的购物车列表
            const res = await getNewCartApi()
            cartList.value = res.result
        } else {
            cartList.value = cartList.value.filter((item) => skuId !== item.skuId)
        }
    }

    // 清除购物车
    const clearCart = () => {
        cartList.value = []
    }

    // 计算总价和总数量
    const allCount = computed(() => cartList.value.reduce((arr, cur) => arr + cur.count, 0))
    const total = computed(() => cartList.value.reduce((arr, cur) => arr + (cur.count * cur.price), 0))
    // 单选
    const singleCheck = (skuId, selected) => {
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = selected
    }
    // 点击全选
    const allCheck = (selected) => {
        cartList.value.forEach(item => {
            item.selected = selected
        });
    }
    // 全选状态
    const isAll = computed(() => cartList.value.every((item) => item.selected))
    // 购物车界面选中商品的数据统计
    //数量
    const selectedCount = computed(() => cartList.value.filter(item => item.selected === true).reduce((arr, cur) => arr + cur.count, 0))
    //总价
    const selectedTotal = computed(() => cartList.value.filter(item => item.selected === true).reduce((arr, cur) => arr + (cur.count * cur.price), 0))
    return {
        singleCheck,
        cartList,
        addCart,
        delCart,
        total,
        allCount,
        isAll,
        allCheck,
        selectedCount,
        selectedTotal,
        clearCart,
        updateNewCartList
    }
}, {
    persist: true
})

